package com.usian.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usian.article.entity.ApArticle;
import com.usian.article.entity.ApArticleContent;
import com.usian.article.entity.ApAuthor;
import com.usian.article.entity.ApCollection;
import com.usian.article.mapper.ApArticleMapper;
import com.usian.article.service.IApArticleContentService;
import com.usian.article.service.IApArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.article.service.IApAuthorService;
import com.usian.article.service.IApCollectionService;
import com.usian.behavior.feign.BehaviorFeign;
import com.usian.common.enums.AppHttpCodeEnum;
import com.usian.common.exception.LeadException;
import com.usian.common.threadlocal.UserThreadLocalUtils;
import com.usian.common.util.BeanHelper;
import com.usian.model.article.dtos.ArticleDto;
import com.usian.model.article.dtos.ArticleHomeDto;
import com.usian.model.article.dtos.ArticleInfoDto;
import com.usian.model.media.dtos.WmNewsResultDTO;
import com.usian.user.feign.UserFeign;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 文章信息表，存储已发布的文章 服务实现类
 * </p>
 *
 * @author usian
 * @since 2022-07-12
 */
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements IApArticleService {

    @Autowired
    private IApAuthorService apAuthorService;

    @Autowired
    private IApArticleContentService apArticleContentService;

    @Override
    public Long saveArticle(WmNewsResultDTO dto) {
        //保存文章数据
        ApArticle apArticle = new ApArticle();
        apArticle.setTitle(dto.getTitle());
        //根据自媒体用户id查询作者
        QueryWrapper<ApAuthor> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ApAuthor::getWmUserId, dto.getWmUserId());
        ApAuthor apAuthor = apAuthorService.getOne(queryWrapper);
        if (apAuthor == null) {
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST, "文章作者不存在");
        }
        apArticle.setAuthorId(apAuthor.getId());
        apArticle.setAuthorName(apAuthor.getName());
        apArticle.setChannelId(dto.getChannelId());
        apArticle.setChannelName(dto.getChannelName());
        apArticle.setLayout(dto.getType());
        apArticle.setFlag(0);
        apArticle.setImages(dto.getImages());
        apArticle.setLabels(dto.getLabels());
        apArticle.setCreatedTime(new Date());
        apArticle.setPublishTime(dto.getPublishTime());
        apArticle.setIsComment(true);
        apArticle.setIsForward(true);
        apArticle.setIsDelete(false);
        apArticle.setIsDown(false);
        apArticle.setWmNewsId(dto.getId());

        boolean b = save(apArticle);
        if (!b) {
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR, "保存app文章失败");
        }
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContent.setContent(dto.getContent());
        boolean b1 = apArticleContentService.save(apArticleContent);
        if (!b1) {
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR, "保存文章失败");
        }

        return apArticle.getId();
    }

    @Override
    public void upOrDown(Map<String, Integer> map) {
        //根据自媒体文章id更新App文章上下架状态
        UpdateWrapper<ApArticle> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(ApArticle::getWmNewsId, map.get("wmNewsId")).set(ApArticle::getIsDown, map.get("enable") == 0 ? true : false);
        boolean b = update(updateWrapper);
        if (!b) {
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR, "保存app文章上下架失败");
        }
    }


    @Override
    public List<ArticleDto> load(ArticleHomeDto dto, int status) {
        //参数校验
        if (dto == null) {
            throw new LeadException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //设置分页查询条件
        Integer size = dto.getSize();
        if (size == null || size == 0) {
            size = 10;
        }
        Page<ApArticle> page = new Page<>(1, size);
        //设置页面查询条件
        QueryWrapper<ApArticle> queryWrapper = new QueryWrapper<>();
        //设置频道id条件
        if (StringUtils.isNotBlank(dto.getTag()) && !dto.getTag().equals("__all__")) {
            queryWrapper.lambda().eq(ApArticle::getChannelId, dto.getTag());
        }
        //设置时间查询条件
        if (status == 1) {
            //加载更多文章列表，小于页面传来得最小时间
            queryWrapper.lambda().lt(ApArticle::getPublishTime, dto.getMinBehotTime());
        } else {
            //加载更多文章列表，小于页面传来得最大时间g
            queryWrapper.lambda().gt(ApArticle::getPublishTime, dto.getMaxBehotTime());

        }
        //设置被下架，未删除状态条件,基于发布时间降序
        queryWrapper.lambda().eq(ApArticle::getIsDown, false).eq(ApArticle::getIsDelete, false).orderByDesc(ApArticle::getPublishTime);
        //执行分页条件查询
        IPage<ApArticle> iPage = this.page(page, queryWrapper);
        if (iPage == null || CollectionUtils.isEmpty(iPage.getRecords())) {
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //数据转换
        List<ArticleDto> articleDtoList = BeanHelper.copyWithCollection(page.getRecords(), ArticleDto.class);

        return articleDtoList;

    }

    @Autowired
    private IApCollectionService apCollectionService;

    @Override
    public Map<String, Object> loadArticleInfo(ArticleInfoDto dto) {
        Map<String, Object> map = new HashMap<>();
        //参数校验
        if (dto == null || dto.getArticleId() == null) {
            throw new LeadException(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        ApArticle apArticle = getById(dto.getArticleId());
        if (apArticle == null) {
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }

        //查询文章的内容
        QueryWrapper<ApArticleContent> queryWrapperContent = new QueryWrapper<>();
        queryWrapperContent.lambda().eq(ApArticleContent::getArticleId, dto.getArticleId());
        ApArticleContent apArticleContent = apArticleContentService.getOne(queryWrapperContent);

        ArticleDto articleDto = BeanHelper.copyProperties(apArticle, ArticleDto.class);
        map.put("config", articleDto);
        map.put("content", apArticleContent);
        return map;
    }

    @Autowired
    private BehaviorFeign behaviorFeign;

    @Autowired
    private UserFeign userFeign;


    @Override
    public Map<String, Boolean> loadArticleBehavior(ArticleInfoDto dto) {
        //参数校验
        if (dto == null) {
            throw new LeadException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //获取登录用户
        Integer userId = UserThreadLocalUtils.getUserId();
        boolean isUser = false;
        if (userId != null && userId != 0) {
            isUser = true;
        }
        if (userId == null && dto.getEquipmentId() == null) {
            throw new LeadException(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //调用行为微服务，查询用户点赞和不喜欢行为
        Map<String, Boolean> map = behaviorFeign.findBehavior(userId, dto.getEquipmentId(), dto.getArticleId(), 0);
        //调用用户微服务，查询用户关注行为
        boolean isFollow = false;
        if (isUser) {
            //因为关注操作是要求用户必须是登录状态才能执行操作
            ApAuthor apAuthor = apAuthorService.getById(dto.getAuthorId());
            if (apAuthor != null) {
                Integer followId = apAuthor.getUserId();
                Boolean boo = userFeign.findByUserIdAndFollowId(userId, followId);
                if (boo) {
                    isFollow = true;
                }
            }
        }
        //查询用户收藏得行为（本地调用）
        QueryWrapper<ApCollection> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ApCollection::getArticleId,dto.getArticleId()).eq(ApCollection::getType,0);
        if (isUser) {
            queryWrapper.lambda().eq(ApCollection::getApUserId,userId);
        }else {
            queryWrapper.lambda().eq(ApCollection::getEquipmentId,dto.getEquipmentId());
        }
        ApCollection apCollection = apCollectionService.getOne(queryWrapper);
        boolean iscollection=false;
        if (apCollection != null && apCollection.getOperation()==1) {
            iscollection=true;
        }

        //查询用户收藏得行为（本地调用）
        map.put("isfollow", isFollow);
        map.put("iscollection",iscollection);
        return map;
    }

    /**
     * 分页查询文章信息
     * @param page
     * @param size
     * @return
     */
    @Override
    public List<ArticleDto> findArticleByPage(int page, int size) {
        //设置分页条件
        Page<ApArticle> page1 = new Page<>(page,size);
        //设置查询条件：非下架，非删除文章
        QueryWrapper<ApArticle> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ApArticle::getIsDown,false).eq(ApArticle::getIsDelete,false);
        //执行查询
        IPage<ApArticle> iPage = this.page(page1, queryWrapper);
        if (iPage==null|| CollectionUtils.isEmpty(iPage.getRecords())){
           throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST,"满足条件得文章不存在");
        }
        //数据转换
        List<ArticleDto> articleDtoList = BeanHelper.copyWithCollection(iPage.getRecords(), ArticleDto.class);


        return articleDtoList;
    }
}
